package com.example.myapplication7

import android.annotation.SuppressLint
import android.app.Service
import android.content.Intent
import android.media.MediaPlayer
import android.os.Binder
import android.os.IBinder
import android.app.PendingIntent
import java.io.IOException
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import androidx.annotation.RequiresApi

class MusicService : Service() {

    companion object{
        val Commond = "operate"
    }
    val mediaPlayer = MediaPlayer()

    val musicList = mutableListOf<String>()
    val musicNameList = mutableListOf<String>()
    var current = 0;
    var isPause= false;
    val binder = MusicBinder()

    inner class MusicBinder: Binder() {

        val musicName
            get()=musicNameList.get(current)

        var currentPosition
            get()=mediaPlayer.currentPosition
            set(value) = mediaPlayer.seekTo(value)

        val duration
            get()=mediaPlayer.duration

        val size
            get()=musicList.size

        val currentIndex
            get()=current
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate() {
        super.onCreate()
        getMusicList()
        mediaPlayer.setOnPreparedListener {
            it.start()
        }
        mediaPlayer.setOnCompletionListener {
            current++;
            if(current>=musicList.size){
                current=0;
            }
            play()
        }
    }
    @RequiresApi(Build.VERSION_CODES.O)
    private fun createNotification(musicName: String) {
        val channelId = "music_channel"
        val channelName = "Music Player Channel"

        // 创建NotificationChannel（仅对Android O及以上版本）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationChannel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW)
            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(notificationChannel)
        }

        // 创建Intent，用于打开MainActivity
        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)

        // 创建Notification
        val notificationBuilder = Notification.Builder(this, channelId)
            .setContentTitle("正在播放")
            .setContentText(musicName)
            .setSmallIcon(R.drawable.ic_notification) // 请确保你有一个名为ic_notification的图标资源
            .setVisibility(Notification.VISIBILITY_PUBLIC)
            .setPriority(Notification.PRIORITY_LOW)
            .setContentIntent(pendingIntent) // 设置点击通知时的意图
            .setAutoCancel(true) // 点击通知后自动取消

        // 显示Notification
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.notify(1, notificationBuilder.build())
    }


    @RequiresApi(Build.VERSION_CODES.O)
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val operate = intent?.getIntExtra(Commond,1)?:1
        when(operate){
            1->play()
            2->pause()
            3->stop()
            4->next()
            5->prev()
        }

        return super.onStartCommand(intent, flags, startId)
    }

    override fun onBind(p0: Intent?): IBinder{
        return binder
    }

    fun pause() {
        if(isPause){
            mediaPlayer.start()
            isPause = false
        }else {
            mediaPlayer.pause()
            isPause = true
        }
    }
    @RequiresApi(Build.VERSION_CODES.O)
    fun next() {
        current++;
        if(current>=musicList.size){
            current=0;
        }
        play()
    }
    fun stop() {
        mediaPlayer.stop()
        stopSelf()
    }
    @RequiresApi(Build.VERSION_CODES.O)
    fun prev() {
        current--
        if(current<0){
            current=musicList.size-1;
        }
        play()
    }

    @RequiresApi(Build.VERSION_CODES.O)
    @SuppressLint("SetTextI18n")
    fun play(){
        if(musicList.size==0){
            return
        }
        val path = musicList[current]
        mediaPlayer.reset()
        try {
            mediaPlayer.setDataSource(path)
            mediaPlayer.prepareAsync()
            // 当音乐准备就绪并开始播放时显示通知
            mediaPlayer.setOnPreparedListener {
                it.start()
                createNotification(musicNameList[current])
            }
        }catch (e: IOException){
            e.printStackTrace()
        }
    }

    @SuppressLint("Range")
    private fun getMusicList() {
        val cursor = contentResolver.query(
            android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            null,
            null,
            null,
            null
        )
        if (cursor != null) {
            while (cursor.moveToNext()) {
                val musicPath = cursor.getString(cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.DATA))
                musicList.add(musicPath)
                val musicName = cursor.getString(cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE))
                musicNameList.add(musicName)
            }
            cursor.close()
        }
    }
}